package com.intco.ait.quotation.api.common.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author Angus
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    /**
     * Spring应用上下文环境
     */
    private static ApplicationContext applicationContext;

    private static String applicationName;
    private static String port;
    private static String env;

    private static int corePoolSize;

    @Value("${current.limit.scheduled.corePoolSize:10}")
    public void setCorePoolSize(int corePoolSize) {
        SpringContextUtil.corePoolSize = corePoolSize;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
        SpringContextUtil.applicationName = applicationContext.getEnvironment().getProperty("spring.application.name");
        SpringContextUtil.applicationName = SpringContextUtil.applicationName == null ? "application" : SpringContextUtil.applicationName;
        SpringContextUtil.port = applicationContext.getEnvironment().getProperty("server.port");
        SpringContextUtil.port = SpringContextUtil.port == null ? "8080" : SpringContextUtil.port;
        SpringContextUtil.env = applicationContext.getEnvironment().getActiveProfiles()[0];
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static String getPort() {
        return port;
    }

    public static String getApplicationName() {
        return applicationName;
    }

    public static String getEnv() {
        return env;
    }

    public static Object getBean(String name) throws BeansException {
        return applicationContext.getBean(name);
    }

    public static int getCorePoolSize() {
        return corePoolSize;
    }

    public static <T> T getBean(Class<T> clz) throws BeansException {
        return applicationContext.getBean(clz);
    }
}
